package com.example.im.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.example.common.base.AbsActivity;
import com.example.common.interfaces.CommonCallback;
import com.example.common.interfaces.KeyboardHeightChangeListener;
import com.example.common.utils.DisplayUtils;
import com.example.common.utils.KeyboardHeightUtils;
import com.example.common.utils.L;
import com.example.common.utils.SPUtils;
import com.example.im.R;
import com.example.im.adapter.ChatAdapter;
import com.example.im.bean.MessageBean;
import com.example.im.databinding.ActChatBinding;
import com.example.im.utils.MessageUtils;
import com.example.im.utils.RouterUtils;
import com.tencent.imsdk.v2.V2TIMMessage;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import static com.example.common.utils.SPUtils.IM_LOGIN;
import static com.example.common.utils.SPUtils.IM_PHOTO;

//@Route(path = RouterUtils.IM_CHAT)
@Route(path="/im/chat")
public class ChatActivity extends AbsActivity<ActChatBinding> implements KeyboardHeightChangeListener {

    private String uid;
    private KeyboardHeightUtils keyboardHeightUtils;
    private LinearLayoutManager adapterLayoutManager;
    private List<MessageBean> messageList;
    private boolean mPaused;
    private String nickName;
    private ChatAdapter mAdapter;
    private int mKeyboardHeight;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.act_chat;
    }

    @Override
    protected void main() {
        init();
        initAdapter();
        getMessage();
    }

    private void init() {
        uid = getIntent().getStringExtra("uid");
        nickName = getIntent().getStringExtra("name");
        //设置标题栏
        mBinding.tvTitle.setText(nickName);
        messageList = new ArrayList<MessageBean>();
        //设置键盘监听
        keyboardHeightUtils = new KeyboardHeightUtils(findViewById(android.R.id.content), this);
        mBinding.llRoot.postDelayed(() -> keyboardHeightUtils.start(), 500);
        keyboardHeightUtils.onGlobalLayout();
    }

    private void initAdapter() {
        mAdapter = new ChatAdapter(messageList);
        adapterLayoutManager = new LinearLayoutManager(mContext);
        mBinding.rvChat.setLayoutManager(adapterLayoutManager);
        mBinding.rvChat.setAdapter(mAdapter);
    }

    private void onKeyboardChange(int visibleHeight, int keyboardHeight) {
        if (keyboardHeight != 0) {
            mBinding.llConView.scrollBy(0, keyboardHeight);
            adapterLayoutManager.scrollToPositionWithOffset(messageList.size() - 1, -DisplayUtils.dpToPx(20));
        } else {
            mBinding.llConView.scrollBy(0, -mKeyboardHeight);
        }
        this.mKeyboardHeight = keyboardHeight;
    }

    @Override
    protected void initListener() {
        mBinding.btnSend.setOnClickListener(v -> {
            MessageBean bean = new MessageBean();
            bean.setSenderId(SPUtils.getInstance().getStringValue(IM_LOGIN));
            bean.setHeadPhoto(SPUtils.getInstance().getStringValue(IM_PHOTO));
            bean.setSendTime(System.currentTimeMillis());
            bean.setMessageType(V2TIMMessage.V2TIM_ELEM_TYPE_TEXT);
            bean.setTextMessage(mBinding.etMessage.getText().toString());
            bean.setStatus(MessageBean.STATUS_SENDING);
            messageList.add(bean);
            mAdapter.notifyItemRangeInserted(messageList.size() - 1, 1);
            mBinding.rvChat.scrollToPosition(messageList.size() - 1);
            MessageUtils.getInstance().sendTextMessage(uid, mBinding.etMessage.getText().toString(), (success, message) -> {
//                if (success) {
//                } else {
//
//                }
            });
        });

        mBinding.ivOther.setOnClickListener(v -> {

        });

        MessageUtils.getInstance().setOnMessageListener(data -> {
            MessageUtils.getInstance().markMessageAsRead(data.getSenderId());
            messageList.add(data);
            mAdapter.notifyItemRangeInserted(messageList.size() - 1, 1);
            mBinding.rvChat.scrollToPosition(messageList.size() - 1);
        });

        mBinding.etMessage.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    mBinding.btnSend.setVisibility(View.VISIBLE);
                    mBinding.ivOther.setVisibility(View.GONE);
                } else {
                    mBinding.btnSend.setVisibility(View.GONE);
                    mBinding.ivOther.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    public void onHeightChangedListener(int visibleHeight, int keyboardHeight) {
        if (mPaused) {
            return;
        }
        L.e(TAG, "onHeightChangedListener keyboardHeight==" + keyboardHeight);
        onKeyboardChange(visibleHeight, keyboardHeight);
    }

    @Override
    public boolean isSoftInputShowed() {
        if (keyboardHeightUtils != null) {
            return keyboardHeightUtils.isSoftInputShowed();
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPaused = false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPaused = true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        keyboardHeightUtils.release();
    }

    private void getMessage() {
        MessageUtils.getInstance().getMessageList(uid, 20, null, new CommonCallback<List<MessageBean>>() {

            @Override
            public void callback(List<MessageBean> data) {
                if (data == null || data.size() == 0) {
                    return;
                }
                MessageUtils.getInstance().markMessageAsRead(uid);
                messageList.addAll(data);
                mAdapter.notifyDataSetChanged();
                mBinding.rvChat.scrollToPosition(data.size() - 1);
            }
        });
    }

}
